import { Button, FormInstance } from "antd";
import { createContext, useEffect, useRef, useState, MutableRefObject } from "react";
import { getSource } from "src/api";
import { PageData } from "src/util";
import { RoleRecord } from "./RoleType";
import { ImgUploadRef } from "src/components/dataEntry/ImgUpload";
import RoleInfoDrawer from "./components/RoleInfoDrawer";
import RoleList, { RoleListRef } from "./components/RoleList";
import PermissionDrawer from "./components/PermissionDrawer";

interface RoleContextProps {
	operatedRole: MutableRefObject<RoleRecord | null>;
}

export const RoleContext = createContext<RoleContextProps>({
	operatedRole: { current: null },
});

const Role = () => {
	const [roles, setRoles] = useState<RoleRecord[]>([]);
	const roleInfoFormRef = useRef<FormInstance | null>(null);
	const uploadRef = useRef<ImgUploadRef>(null);
	const [operationMode, setOperationMode] = useState<"find" | "edit" | "add">("find");
	const operatedRole = useRef<RoleRecord | null>(null);
	const roleListRef = useRef<RoleListRef>(null);

	const [roleInfoDrawerShow, setRolInfoDrawerShow] = useState(false);
	const [authDrawerShow, setAuthDrawerShow] = useState(false);

	const fetchRoles = async () => {
		const pageInfo = roleListRef.current?.getPageInfo();
		const result = await getSource<PageData<RoleRecord[]>>({
			source: "role",
			page: pageInfo?.current || 1,
			pageSize: pageInfo?.pageSize || 0,
			sort: { createdTime: 1 },
		});
		setRoles(result.data?.data || []);
		roleListRef.current?.setTotal(Number(result.data?.total) || 0);
		return;
	};

	useEffect(() => {
		fetchRoles();
	}, []);

	return (
		<RoleContext.Provider value={{ operatedRole }}>
			<Button
				className="mb-3"
				type="primary"
				onClick={() => {
					roleInfoFormRef.current?.resetFields();
					setRolInfoDrawerShow(true);
					setOperationMode("add");
				}}
			>
				添加角色
			</Button>
			<RoleList
				ref={roleListRef}
				formRef={roleInfoFormRef}
				uploadRef={uploadRef}
				setAuthVisible={setAuthDrawerShow}
				setInfoVisible={setRolInfoDrawerShow}
				setMode={setOperationMode}
				list={roles}
				fetchList={fetchRoles}
				operatedRecord={operatedRole}
			/>
			{/* 已授权列表抽屉 */}
			<PermissionDrawer visible={authDrawerShow} setVisible={setAuthDrawerShow} operatedRole={operatedRole} />
			{/* 角色信息抽屉 */}
			<RoleInfoDrawer
				setVisible={setRolInfoDrawerShow}
				visible={roleInfoDrawerShow}
				formRef={roleInfoFormRef}
				uploadRef={uploadRef}
				operationMode={operationMode}
				operatedRecord={operatedRole}
				onFinish={fetchRoles}
			/>
		</RoleContext.Provider>
	);
};

export default Role;
